<script lang="ts" setup>
import type { TablePaginationConfig, DrawerProps,  } from 'ant-design-vue';
import { $t } from '@vben/locales';

import type { MinishopSpu, MinishopSpuResponse } from './types.ts';
import type { MinishopCart, MinishopCartResponse } from '../minishop_cart/types.ts';
import type { ComponentSetting, ComponentSettingResponse } from '../../uctoo/component_setting/types.ts';
import { onMounted, reactive, ref, computed, nextTick } from 'vue';
import { message, InputNumber } from 'ant-design-vue';
import editform from './edit.vue';
import { useRoute, useRouter } from 'vue-router';
import { removeEmpty } from '#/utils/common';
import { uctoo_minishop_spu, uctoo_component_setting, uctoo_minishop_cart, uctoo_minishop_order } from '#/store';
import { useRepo } from 'pinia-orm';
import { useAxiosRepo } from '@pinia-orm/axios';
// import Swiper bundle with all modules installed
import Swiper from 'swiper/bundle';
// import styles bundle
import 'swiper/css/bundle';
import { formatPrice } from '#/utils/common';
const router = useRouter();
// 获取当前路由信息
const route = useRoute();
// 获取查询字符串部分
let queryParam = reactive({ ...route.query });
const spuDataSource = ref<MinishopSpu[]>([]);
const currentRecord = ref<MinishopSpu | null>(null);
const currentCart = ref<MinishopCart | null>(null);
const headimgs = ref<string[]>([]);
const descInfo = ref<string[]>([]);
const quantity = ref(1);
const minishopSpuRepo = computed(() => {
  return useRepo(uctoo_minishop_spu)
});
const minishopCartRepo = computed(() => {
  return useRepo(uctoo_minishop_cart)
});

const addToCart = () => {
};

const buyNow = async () => {
  if (!currentRecord.value) {
    message.error('操作失败');
    return
  }else{
    
    const orderData = {
      spu_id:currentRecord.value.id,
      sku_id: '',
      sku_cnt:quantity.value,
      appid: import.meta.env.VITE_WEBSITE_APPID,    //网站应用的appid默认应与服务号appid一致
      user_type:'uctoo_user', //用户类型uctoo_user、wechatopen_users、wechatopen_miniapp_users
    }

  console.log('提交的数据:', orderData)
  const res = await useAxiosRepo(uctoo_minishop_order).api().createUserOrder(orderData);  
  console.log('订单信息:', res)
  if (res && res.response.data.id) {
    // 跳转到订单确认页面
    openTabWithParams(res.response.data.id)
  } else {
    message.error('操作失败');
  }
  }
  
};
const increaseQuantity = () => {
  quantity.value++
}

const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--
  }
}

function openTabWithParams(id: string) {
  // 这里就是路由跳转，也可以用path
  const params = { id: id };
  router.push({ name: 'minishop.minishop_order.confirm', state: { params } });
}

onMounted(() => {
  console.log(import.meta.env.VITE_APP_TITLE);
  console.log(import.meta.env.VITE_WEBSITE_APPID);
spuDataSource.value = minishopSpuRepo.value.all() as unknown as MinishopSpu[];
console.log(spuDataSource.value);
console.log(queryParam.id);
const historyParams = history.state;
console.log(historyParams);
 if(historyParams.params?.id){
    const res = minishopSpuRepo.value
    .query()
    .where('id',String(historyParams.params.id))
    .first();
  console.log('res', res); 
  currentRecord.value = res as unknown as MinishopSpu;
  console.log('currentRecord', currentRecord.value); 
  headimgs.value = JSON.parse(currentRecord.value?.headimg ?? '[]');
  console.log('headimgs', headimgs.value);
  descInfo.value = JSON.parse(currentRecord.value?.desc_info ?? '[]');
  //需要在数据加载后初始化swiper。 Reinitialize Swiper after headimgs is updated
  nextTick(() => {
    new Swiper('.swiper', {
      direction: 'horizontal',
      loop: true,
      pagination: {
        el: '.swiper-pagination',
      },
      scrollbar: {
        el: '.swiper-scrollbar',
      },
    });
  });

  
  
  } /**/


  /* register();
  const swiper = document.querySelector('swiper-container');
  if (swiper) {
    swiper.initialize();
  } 
  const swiper = new Swiper('.swiper', {
  // Optional parameters
  direction: 'horizontal',
  loop: true,

  // If we need pagination
  pagination: {
    el: '.swiper-pagination',
  },

  // And if we need scrollbar
  scrollbar: {
    el: '.swiper-scrollbar',
  },
});*/
});
</script>

<template>
  <div class="p-4">
    <a-card :bordered="false">
      <a-empty v-if="!currentRecord" />
      <div v-else-if="currentRecord"  >
      
        <!-- Slider main container -->
        <a-row gutter="16">
          <!-- First Row -->
          <a-col :span="12">
            <!-- Swiper -->
            <div class="swiper">
              <div class="swiper-wrapper">
                <div 
                  v-for="(img, index) in headimgs" 
                  :key="index" 
                  class="swiper-slide"
                >
                  <img :src="img" alt="Product Image" class="product-image" />
                </div>
              </div>
              <div class="swiper-pagination"></div>
              <div class="swiper-scrollbar"></div>
            </div>
          </a-col>
          <a-col :span="12">
            <!-- Product Info -->
            <div>
              <h2>{{ currentRecord?.title }}</h2>
              <h3>{{ currentRecord?.subtitle }}</h3>
              <p>{{ currentRecord?.attrs }}</p>
              <p>¥{{ formatPrice(String(currentRecord?.min_price)) }}元</p>
            </div>

            <!-- Product Actions -->
            <div class="product-actions">
              <!-- Quantity Selector -->
              <a-space>
                <div class="quantity-control">
                  <a-button class="quantity-btn" @click="decreaseQuantity">-</a-button>
                  <text class="quantity">{{ quantity }}</text>
                  <a-button class="quantity-btn" @click="increaseQuantity">+</a-button>
                </div>

              <!-- Action Buttons -->
              <div class="action-buttons">
                <a-space>
                <a-button 
                  type="primary" danger 
                  class="buy-now" 
                  @click="buyNow"
                >
                  立即购买
                </a-button>
                <a-button 
                  type="primary" 
                  class="add-to-cart" 
                  @click="addToCart"
                >
                  加入购物车
                </a-button>
                
              </a-space>
              </div>
              </a-space>
            </div>
          </a-col>
        </a-row>

        <!-- Second Row -->
        <a-row gutter="16" class="mt-4">
          <a-col :span="24">
            <!-- Product Detail Images -->
            <div v-for="(img, index) in descInfo" :key="index" class="detail-image">
              <img :src="img" alt="Detail Image" class="product-detail-image" />
            </div>
          </a-col>
        </a-row>
      </div><!--end Product detail -->
    </a-card>
  </div>
</template>
<style scoped>
.swiper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 320px;
  height: 320px;
  overflow: hidden;
}

.product-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.swiper-wrapper {
  display: flex;
}

.swiper-slide {
  display: flex;
  justify-content: center;
  align-items: center;
}

.product-actions {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
}

.quantity-control {
  display: flex;
  gap: 5rpx;
  align-items: center;
  margin-top: 20rpx;
}

.quantity-btn {
  width: 60rpx;
  height: 60rpx;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24rpx;
  gap: 5rpx;
}
</style>
